import changeValue from "./change-value";
import ExcelStore from "../../ExcelStore";
import pasteData from "./paste-data";
import clearContent from "./clearContent";
import insertRow from "./insert-row";
import deleteRows from "./delete-rows";
import jQuery from 'jquery';
import * as API from "../../../../apis/excelsearch";
import { message } from "antd";
import { Modal } from "antd";
import { getLabel } from "../../../../util/convert";
function r(a) {
    var b, c, d, e, f, g: any[] = [];
    if (a) {
        for (b = '"',
            c = !1,
            d = 0; d < a.length; d++)
            e = d > 0 ? a[d - 1] : "",
                f = a[d],
                f === b ? (c = !c,
                    g.push(b)) : c || "\n" !== f || "\r" === e ? g.push(f) : g.push("\r\n");
        return g.join("")
    }
    return ""
}





export const register = (commandManager: GC.Spread.Commands.CommandManager, store: ExcelStore) => {
    commandManager.register('cube-change-value', changeValue);
    commandManager.register('cube-paste-data', pasteData);
    delete (commandManager as any).clear;
    delete (commandManager as any).clearValues;
    commandManager.register('clear', clearContent, GC.Spread.Commands.Key.del);
    commandManager.register('clear', clearContent, GC.Spread.Commands.Key.backspace);

    commandManager.register('cube-insert-rows', insertRow);
    commandManager.register('cube-delete-rows', deleteRows);

    store.workbook.commandManager().register("gc.spread.undo",
    {
        canUndo: true,
        execute: function (context, options, isUndo) {
            if (isUndo) {
               } else {
                var sheet = store.workbook.getActiveSheet();
                var selections = sheet.getSelections();
                // var lineStyle = GC.Spread.Sheets.LineStyle.thin;
                // var lineBorder = new GC.Spread.Sheets.LineBorder('#a5a5a5',lineStyle);
                if(selections && selections.length > 0){
                    let oldColor="";
                    //挂起sheet绘制
                    sheet.suspendPaint();                   
                    selections.forEach(function (item) {
                        var cellRange = sheet.getRange(item.row, item.col, item.rowCount, item.colCount);
                        const cell =  store.workbook.getActiveSheet().getCell(item.row, item.col);
                        oldColor = cell.backColor()===void 0 ?"":cell.backColor();
                        //获取配置颜色区域的行(id)-字段-颜色
                        const {row,col,rowCount,colCount} = item;
                        const datas = store.dataSource.getValue('datas') as any[];
                        const columns = store.columns;
                        let colordatas : any = [];
                        for (let i =0; i < rowCount; i++) {
                            const data = datas[row+i] || {};             
                        //  const id = data.randomFieldSubKeyd_id ? `${data.randomFieldId}^^--^^${data.randomFieldSubKeyd_id}` : data.randomFieldId;
                            const id = data.randomFieldId;
                            for (let j = 0; j < colCount; j++) {
                                const fieldid = columns[col+j].id() as string;
                                colordatas.push({id:id,fieldid:fieldid,color:'',oldColor:oldColor});              
                            }          
                        }     
                        API.checkColorIsChange({colordatas:JSON.stringify(colordatas),...store.params,time:store.colortime}).then((data:any)=>{
                            if(data.status == "1"){
                                if(data.errMessage){//颜色过期刷新后重新设置
                                    Modal.info({
                                        title: getLabel(15172, '系统提示'),
                                        content:getLabel('','所选区域内存在过期的颜色,请刷新数据后,重新设置颜色'),
                                        onOk() { return; },
                                    })
                                }else{
                                    API.cellColor({ type:'undo',colordatas:JSON.stringify(colordatas),...store.params}).then(()=>{
                                     cellRange.backColor('');
                                    store.getCellColor(store.data); 
                                    });
                                }
                            }else{
                                message.error("校验数据是否过期出现异常");
                            }
                        })       
                    });
                    //重绘
                    sheet.resumePaint();
                }
               }
        }      
    });

       store.workbook.commandManager().register("colorPicker_backColor",
       {
           canUndo: true,
           execute: function (context, options, isUndo) {
            //   var Commands = GC.Spread.Sheets.Commands;
               // 在此加cmd
               options.cmd = "colorPicker_backColor";
               if (isUndo) {
               } else {
                // Commands.startTransaction(context, options);
                   changeColor(store.workbook, options.color, true);
                // Commands.endTransaction(context, options);
                   return true;
               }
               store.workbook.resumePaint();
           }
          
       });

   /*
    *  创建颜色选择面板，并注册事件
    * */
   function createColorpicker(flag) {
    var colors = ['rgb(255,255,255)',
        'rgb(0,255,255)', 'rgb(255,0,255)',
        'rgb(255,255,0)', 'rgb(255,0,0)',
        'rgb(0,255,0)', 'rgb(0,0,255)',
        'rgb(0,0,0)', 'rgb(64,64,64)',
        'rgb(128,128,128)'];
    var colorPicker = jQuery("<div id='colorPicker'></div>");
    for(var i=0; i<colors.length; i++){
        var color = jQuery("<span class='cube_colorPicker cube_colorPickerBorderMouseout' mycolor='"+colors[i]+"' style='background-color:"+colors[i]+"'></span>");
        color.mouseenter(function () {
            jQuery(this).removeClass("cube_colorPickerBorderMouseout");
            jQuery(this).addClass("cube_colorPickerBorderMouseenter");
        });
        color.mouseout(function () {
            jQuery(this).removeClass("cube_colorPickerBorderMouseenter");
            jQuery(this).addClass("cube_colorPickerBorderMouseout");
        });
        color.click(function () {
            var that = jQuery(this);
            var color = that.attr("mycolor");
           
            var sheet =  store.workbook.getActiveSheet();
            var commandName = "colorPicker_foreColor";
            if(flag){
                commandName = "colorPicker_backColor";
            }
            store.workbook.commandManager().execute({
                cmd: commandName,
                sheetName: sheet.name(),
                color : color
            });
        });
        colorPicker.append(color);
    }
    return colorPicker;
}


    function ContextMenu(){}
    ContextMenu.prototype = new GC.Spread.Sheets.ContextMenu.ContextMenu();
        //onOpenMenu是在右键点击时触发的事件
        ContextMenu.prototype.onOpenMenu = function (menuData, itemsDataForShown, hitInfo, spread) {
                var index = -1;
                for(let i=0; i<itemsDataForShown.length; i++){
                    var item = itemsDataForShown[i];
                    if(item.name === "gc.spread.filter"){
                        index = i;
                        break;
                    }
                }
                if(index > -1){
                    itemsDataForShown.splice(index, 1);
                }
                return false;
            };


    var contextMenu = new ContextMenu();
    store.workbook.contextMenu = contextMenu;


    // 通过重写MenuView类，将自定义功能加入右键样式
    function CustomMenuView() { }

    CustomMenuView.prototype = new GC.Spread.Sheets.ContextMenu.MenuView();
    CustomMenuView.prototype.createMenuItemElement = function (menuItemData) {
       var self = this;
       var menuItemView = GC.Spread.Sheets.ContextMenu.MenuView.prototype.createMenuItemElement.call(self, menuItemData);
       if (menuItemData.name === "selectColorPicker1") {
        jQuery(menuItemView).append(createColorpicker(true));
        return menuItemView;
    } else if (menuItemData.name === "selectColorPicker2") {
        jQuery(menuItemView).append(createColorpicker(false));
        return menuItemView;
    }else {
        return menuItemView;
    }
   };
        // 将自定义MenuView赋值给SpreadJS
        store.workbook.contextMenu.menuView = new CustomMenuView();

    const colorPickers = [{
        text: "颜色选择器",
        name: "gc.spread.colorPicker",
        workArea: "viewport",
        subMenu:
            [{
                text: "背景色:",
                name: "selectColorPicker1"
            }
            // ,{
            //     text: "字体色:",
            //     name: "selectColorPicker2"
            // }
        ]
    },
    {
        text: "撤销",
        name: "gc.spread.undo",
        workArea: "viewport",
    }
];
    // 将colorPicker项添加到右键菜单中
    store.workbook.contextMenu.menuData.splice(1, 0, ...colorPickers);

    store.workbook.contextMenu.menuData = store.workbook.contextMenu.menuData.filter(d=>d.name==='gc.spread.insertRows'||d.name==='gc.spread.deleteRows'||d.name==='gc.spread.colorPicker'||d.name==='gc.spread.undo').map(d=>{
        if(d.name === 'gc.spread.insertRows') {
            d.command = 'cube-insert-rows';
        }else if(d.name==='gc.spread.deleteRows'){
            d.command = 'cube-delete-rows';
        }else if(d.name==='gc.spread.undo'){
            d.command = 'gc.spread.undo';
        }
        return d;
    });

   
   function changeColor(spread, color, flag){
       var sheet = spread.getActiveSheet();
       var selections = sheet.getSelections();
       let oldColor="";
       if(selections && selections.length > 0){
           //挂起sheet绘制
           sheet.suspendPaint();
           selections.forEach(function (item) {
               //获取配置颜色区域的行(id)-字段-颜色
              const {row,col,rowCount,colCount} = item;
    
              let row1;
              if(row == -1){
                  row1 = row+1;
              }else{
                  row1 = row;
              }
               const cellRange = sheet.getRange(row1, item.col, item.rowCount, item.colCount);       
               

               const datas = store.dataSource.getValue('datas') as any[];
               const columns = store.columns;
               let colordatas : any = [];
               let oldColordatas : any = [];
               for (let i =0; i < rowCount; i++) {

                   const data = datas[row1+i] || {};             
                // const id = data.randomFieldSubKeyd_id ? `${data.randomFieldId}^^--^^${data.randomFieldSubKeyd_id}` : data.randomFieldId;
                   const id = data.randomFieldId;
                   for (let j = 0; j < colCount; j++) {
                       const cell =  spread.getActiveSheet().getCell(row1+i, col+j);
                       oldColor = cell.backColor()===void 0 ?"":cell.backColor();
                       const fieldid = columns[col+j].id() as string;
                       if(oldColor!=''){
                        oldColordatas.push({id:id,fieldid:fieldid,oldColor:oldColor});
                       }                     
                       colordatas.push({id:id,fieldid:fieldid,color:color,oldColor:oldColor});              
                   }          
               }   
               let type="modify";
               if(oldColordatas.length===0){ 
                   type="add";
               }          
               API.checkColorIsChange({colordatas:JSON.stringify(colordatas),...store.params,time:store.colortime}).then((data:any)=>{
                   if(data.status == "1"){
                       if(data.errMessage){//颜色过期刷新后重新设置
                           Modal.info({
                               title: getLabel(15172, '系统提示'),
                               content:getLabel('','所选区域内存在过期的颜色,请刷新数据后,重新设置颜色'),
                               onOk() { return; },
                           })
                       }else{
                           API.cellColor({ type:type,colordatas:JSON.stringify(colordatas),...store.params}).then(()=>{
                            // 当flag为true时改变背景色，否则改变字体色(暂时不做)
                            if(flag){
                                cellRange.backColor(color);
                            }else {
                                cellRange.foreColor(color);
                            }
                            store.getCellColor(store.data); 
                           });
                       }
                   }else{
                       message.error("校验数据是否过期出现异常");
                   }
               })  
           });
           //重绘
           sheet.resumePaint();    
       }
   }

    (commandManager as any).paste = undefined;
    (store.workbook as any).uu.KM.removeEventListener('paste', (store.workbook as any).uu.H4);
    (store.workbook as any).uu.KM.addEventListener('paste', (event) => {
        try {
            const sheet = (commandManager as any).xc.getActiveSheet();
            const { clipboardData } = event
            const clipboardManager = (commandManager as any).xc.uu;
            if (clipboardData) {
                const html = clipboardData.getData("text/html");
                const textarea = clipboardManager.I4();
                textarea.innerHTML = html;
                const text = html ? clipboardManager.A$a(textarea, !0) : r(clipboardData.getData("text/plain"));
                textarea.innerHTML = "";
                const pasteEvent = sheet.xx(text);
                pasteEvent.cmd = "clipboardPaste";
                pasteEvent.sheetName = sheet.name();
                pasteEvent.clipboardHtml = html;
                store.clipboardPasted(pasteEvent)
            }
        } catch (e) {

        }
    })
}